function finalShape = ASM(I, estShape, T, s, degree, DmMax, searchLen, MODE, P, b)
I = double(I)/255.0;
[I Idx Idy] = gaussgradient(I, 2); 
I = sqrt(Idx.^2+Idy.^2);
I = I./max(max(I));
imshow(I);

[ShapeX R] = rePositionShape(estShape,s, degree, T);
drawSingleShape(ShapeX, 'r');

for k=1:150
k
    ShapeT = getTargetShape(I, ShapeX,0.5);
    %drawSingleShape(ShapeT, 'g');
    if (MODE==1)
        [shapeT R2 s2 T2] = alignShapePair(estShape, ShapeT);
        %drawSingleShape(BFshape,'b');
        temp = (shapeT-estShape);
        b_j = P'*[temp(1,:) temp(2,:)]';
        %Dm = mahalDistance(blambda, lambda);
        Dm = sqrt(sum(b_j.^2./b));

        if(Dm>DmMax)
            b_j = b_j.*(DmMax/Dm);
        end


        dx_1 = P*b_j;

        dx(1,:) = dx_1(1:64);
        dx(2,:) = dx_1(65:128);
        ShapeX = R2*s2*(estShape + dx) + repmat(T2,1,64);

        if(norm(dx)<0.0005)
            break;
        end
    else
        ShapeX = ShapeT;
    end

end
finalShape = ShapeX;
drawSingleShape(ShapeX,'g');

